<template>
  <el-dialog :title="title" v-model="visible" width="900px" top="5vh" append-to-body :close-on-click-modal="false"
    destroy-on-close @opened="onDialogOpened" @closed="onDialogClosed">
    <div class="user-select-container">
      <el-row :gutter="20">
        <!-- 左侧部门树 -->
        <el-col :span="10">
          <div class="dept-tree-section">
            <div class="section-title">
              <el-icon>
                <OfficeBuilding />
              </el-icon>
              选择部门
            </div>
            <el-tree ref="deptTreeRef" :data="deptTreeData" :props="deptTreeProps" node-key="deptId"
              :highlight-current="true" :expand-on-click-node="false" :check-on-click-node="false"
              @current-change="handleDeptChange" class="dept-tree">
              <template #default="{ node, data }">
                <span class="dept-node">
                  <el-icon>
                    <OfficeBuilding />
                  </el-icon>
                  <span>{{ node.label }}</span>
                  <span class="dept-user-count" v-if="data.userCount !== undefined">({{ data.userCount }}人)</span>
                </span>
              </template>
            </el-tree>
          </div>
        </el-col>

        <!-- 右侧用户列表 -->
        <el-col :span="14">
          <div class="user-list-section">
            <div class="section-title">
              <el-icon>
                <User />
              </el-icon>
              部门用户
              <span v-if="currentDeptName" class="current-dept">（{{ currentDeptName }}）</span>
            </div>

            <!-- 用户列表 -->
            <div class="user-list" v-loading="userListLoading">
              <el-empty v-if="!selectedDeptId" description="请先选择部门" :image-size="60" />
              <el-empty v-else-if="!userListLoading && userList.length === 0" description="该部门暂无用户" :image-size="60" />
              <div v-else class="user-items">
                <div v-for="user in userList" :key="user.userId"
                  :class="['user-item', { 'selected': isUserSelected(user) }]" @click="toggleUserSelection(user)">
                  <el-avatar :src="user.avatar" :size="32" class="user-avatar">
                    <span>{{ user.userName?.charAt(0) || user.nickName.charAt(0) }}</span>
                  </el-avatar>
                  <div class="user-info">
                    <div class="user-name">{{ user.userName || user.nickName }}</div>
                    <div class="user-details">{{ user.deptName || '未分配部门' }}</div>
                  </div>
                  <el-icon v-if="isUserSelected(user)" class="selected-icon">
                    <Check />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 已选择的用户 -->
      <div class="selected-users-section" v-if="tempSelectedUsers.length > 0">
        <div class="section-title">
          <el-icon>
            <UserFilled />
          </el-icon>
          已选择的审核人员（{{ tempSelectedUsers.length }}人）
        </div>
        <div class="selected-users">
          <el-tag v-for="user in tempSelectedUsers" :key="user.userId" closable @close="removeUserSelection(user)"
            class="selected-user-tag">
            <el-icon>
              <User />
            </el-icon>
            {{ user.userName || user.nickName }}
          </el-tag>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmSelection" :disabled="tempSelectedUsers.length === 0">
          确 定（{{ tempSelectedUsers.length }}人）
        </el-button>
        <el-button @click="cancelSelection">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { OfficeBuilding, User, UserFilled, Check } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { deptTreeSelect, listUserByDeptId, type OtherDeptVO, type OtherUserVO } from '@/api/other/user/index';

// 定义部门数据类型（扩展支持树形结构）
interface DeptData extends OtherDeptVO {
  children?: DeptData[];
}

// 使用Other模块的用户类型
type UserData = OtherUserVO;

// Props定义
interface Props {
  visible: boolean;
  title?: string;
  selectedUsers?: any[]; // 当前已选择的用户（向后兼容，优先级较低）
  // 推荐使用：支持直接传入ID和姓名字符串格式（优先级较高）
  selectedUserIds?: string; // 逗号分隔的用户ID字符串
  selectedUserNames?: string; // 逗号分隔的用户姓名字符串
  multiple?: boolean; // 是否支持多选
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  title: '选择审核人员',
  selectedUsers: () => [],
  selectedUserIds: '',
  selectedUserNames: '',
  multiple: true
});

// Emits定义
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'confirm': [users: any[]];
  'confirmWithIds': [data: { users: any[]; userIds: string; userNames: string; }];
  'cancel': [];
  'removeUser': [userId: string];
}>();

// 响应式数据
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 部门树相关
const deptTreeRef = ref();
const deptTreeData = ref<DeptData[]>([]);
const deptTreeProps = {
  children: 'children',
  label: 'deptName'
};

// 用户列表相关
const selectedDeptId = ref<string | number>('');
const currentDeptName = ref('');
const userList = ref<UserData[]>([]); // 使用UserData类型
const userListLoading = ref(false);
const tempSelectedUsers = ref<any[]>([]); // 临时选择的用户

// 处理初始选择用户数据的工具函数
const parseSelectedUsers = (userIds: string, userNames: string): any[] => {
  if (!userIds || !userNames) return [];

  const ids = userIds
    .split(',')
    .map((id) => id.trim())
    .filter((id) => id);
  const names = userNames
    .split(',')
    .map((name) => name.trim())
    .filter((name) => name);

  // 确保ID和姓名数量一致
  if (ids.length !== names.length) {
    console.warn('UserSelector: userIds和userNames数量不匹配', { ids, names });
    return [];
  }

  return ids.map((id, index) => ({
    userId: id,
    userName: names[index],
    nickName: names[index],
    deptName: '未分配部门', // 默认值
    deptId: '',
    avatar: ''
  }));
};

// 计算属性：处理初始选中用户数据（优化逻辑）
const initialSelectedUsers = computed(() => {
  // 优先级1：使用字符串格式数据（推荐方式）
  if (props.selectedUserIds && props.selectedUserNames) {
    return parseSelectedUsers(props.selectedUserIds, props.selectedUserNames);
  }

  // 优先级2：使用数组格式数据（向后兼容）
  if (props.selectedUsers && props.selectedUsers.length > 0) {
    return [...props.selectedUsers];
  }

  // 优先级3：无初始数据
  return [];
});

// 监听初始用户数据变化，简化逻辑
watch(
  initialSelectedUsers,
  (newUsers) => {
    tempSelectedUsers.value = [...newUsers];
  },
  { immediate: true }
);

// 构建部门树
const buildDeptTree = (depts: DeptData[], parentId: number | null = null): DeptData[] => {
  const tree: DeptData[] = [];

  for (const dept of depts) {
    if (dept.parentId === parentId) {
      const node: DeptData = {
        deptId: dept.deptId,
        deptName: dept.deptName,
        parentId: dept.parentId,
        children: buildDeptTree(depts, dept.deptId)
      };
      tree.push(node);
    }
  }

  return tree;
};

// 加载部门树
const loadDeptTree = async () => {
  try {
    const response = await deptTreeSelect();
    if (response && response.code === 200) {
      const depts = response.data || [];
      deptTreeData.value = buildDeptTree(depts, 0); // 假设根部门的parentId为0
    }
  } catch (error) { }
};

// 处理部门选择
const handleDeptChange = async (deptData: DeptData) => {
  if (!deptData) return;

  selectedDeptId.value = deptData.deptId;
  currentDeptName.value = deptData.deptName;

  // 加载该部门的用户列表
  await loadUsersByDept(deptData.deptId);
};

// 加载部门用户列表
const loadUsersByDept = async (deptId: string | number) => {
  if (!deptId) return;

  userListLoading.value = true;
  try {
    const response = await listUserByDeptId(deptId);
    if (response && response.code === 200) {
      userList.value = response.data || [];
    }
  } catch (error) {
    console.error('加载部门用户失败:', error);
  } finally {
    userListLoading.value = false;
  }
};

// 判断用户是否已选择
const isUserSelected = (user: UserData) => {
  return tempSelectedUsers.value.some((selected) => selected.userId === user.userId);
};

// 切换用户选择状态
const toggleUserSelection = (user: UserData) => {
  if (!props.multiple && tempSelectedUsers.value.length > 0 && !isUserSelected(user)) {
    // 单选模式下，如果已有选择且当前用户未选中，则替换
    tempSelectedUsers.value = [
      {
        userId: user.userId,
        userName: user.userName,
        nickName: user.nickName,
        deptName: user.deptName || '未分配部门',
        avatar: user.avatar,
        deptId: user.deptId,
      }
    ];
    return;
  }

  const index = tempSelectedUsers.value.findIndex((selected) => selected.userId === user.userId);
  if (index > -1) {
    // 取消选择
    tempSelectedUsers.value.splice(index, 1);
  } else {
    // 添加选择
    tempSelectedUsers.value.push({
      userId: user.userId,
      userName: user.userName,
      nickName: user.nickName,
      deptName: user.deptName || '未分配部门',
      avatar: user.avatar,
      deptId: user.deptId,
    });
  }
};

// 移除用户选择
const removeUserSelection = (user: any) => {
  const index = tempSelectedUsers.value.findIndex((selected) => selected.userId === user.userId);
  if (index > -1) {
    tempSelectedUsers.value.splice(index, 1);
  }
};

// 确认选择
const confirmSelection = () => {

  const selectedUsers = [...tempSelectedUsers.value];

  // 传统的用户数组事件
  emit('confirm', selectedUsers);
  // 新的标准化数据格式事件
  const userIds = selectedUsers.map((user) => user.userId).join(',');
  const userNames = selectedUsers.map((user) => user.userName || user.nickName).join(',');

  emit('confirmWithIds', {
    users: selectedUsers,
    userIds,
    userNames
  });

  visible.value = false;
};

// 取消选择
const cancelSelection = () => {
  emit('cancel');
  visible.value = false;
};

// 对话框打开时
const onDialogOpened = () => {
  loadDeptTree();
};

// 对话框关闭时
const onDialogClosed = () => {
  // 重置状态
  selectedDeptId.value = '';
  currentDeptName.value = '';
  userList.value = [];
  tempSelectedUsers.value = [...(props.selectedUsers || [])];
};
</script>

<style scoped>
/* 用户选择对话框样式 */
.user-select-container {
  min-height: 500px;
  max-height: 70vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.dept-tree-section,
.user-list-section {
  height: 400px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color-light);
  font-weight: 600;
  font-size: 14px;
}

.section-title .el-icon {
  color: var(--el-color-primary);
  font-size: 16px;
}

.current-dept {
  color: var(--el-text-color-regular);
  font-weight: normal;
  font-size: 12px;
}

.dept-tree {
  padding: 8px;
  height: calc(100% - 45px);
  overflow-y: auto;
}

.dept-node {
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
}

.dept-user-count {
  color: var(--el-text-color-regular);
  font-size: 12px;
  margin-left: auto;
}

.user-list {
  height: calc(100% - 45px);
  overflow-y: auto;
  padding: 8px;
}

.user-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.user-item:hover {
  border-color: var(--el-color-primary-light-5);
  background-color: var(--el-color-primary-light-9);
}

.user-item.selected {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-8);
}

.user-avatar {
  flex-shrink: 0;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-weight: 600;
  font-size: 14px;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-details {
  font-size: 12px;
  color: var(--el-text-color-regular);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-top: 2px;
}

.selected-icon {
  color: var(--el-color-primary);
  font-size: 18px;
  flex-shrink: 0;
}

.selected-users-section {
  margin-top: 20px;
  padding: 20px;
  border-top: 1px solid var(--el-border-color-light);
  flex-shrink: 0;
  background-color: var(--el-fill-color-extra-light);
  border-radius: 8px;
  margin-bottom: 0;
}

.selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 12px;
  max-height: 150px;
  overflow-y: auto;
  padding: 8px;
}

.selected-user-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
  border-radius: 6px;
}

.selected-user-tag .el-icon {
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-select-container {
    height: auto;
  }

  .dept-tree-section,
  .user-list-section {
    height: 300px;
  }

  .user-item {
    padding: 8px;
  }

  .user-name {
    font-size: 13px;
  }

  .user-details {
    font-size: 11px;
  }
}
</style>
